import axios from 'axios'


const request = axios.create({
  baseURL: import.meta.env.DEV ? '/api' : 'http://localhost:8080',
  timeout: 10000,
})

request.interceptors.request.use(config => {
  if (config.method === 'post' && !config.headers['Content-Type']) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  }
  return config
})

request.interceptors.response.use(
  res => res.data,
  err => {
    console.error(err)
    return Promise.reject(err)
  }
)

export const blogList = params => {
  const p = new URLSearchParams()
  Object.entries(params).forEach(([k, v]) => {
    if (v !== '' && v != null) p.append(k, v)
  })

  return request.get('/blog/pageList.do', { params: p })
}

export const classList = () => request.get('/class/list.do')

export const deleteBlog = data => request.post('/blog/delete.do', data)

export const insertBlog = data => request.post('/blog/insert.do', data)

export const updateBlog = data => request.post('/blog/update.do', data)

export const uploadFile = data => {
  const form = new FormData()
  form.append('file', data)
  return request.post('/file/upload.do', form, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
}

// 博客详情
export const getBlogDetail = (blogId) => request.get(`/blog/detail.do?id=${blogId}`)

// 评论相关API
export const getComments = (blogId) => request.get(`/comment/list.do?blogId=${blogId}`)

export const addComment = data => request.post('/comment/add.do', data)

export const replyComment = data => request.post('/comment/reply.do', data)

export const deleteComment = data => request.post('/comment/delete.do', data)

// 点赞相关API
export const likeBlog = data => request.post('/like/add.do', data)

export const unlikeBlog = data => request.post('/like/remove.do', data)

export const getLikeStatus = (blogId) => request.get(`/like/status.do?blogId=${blogId}`)

// 收藏相关API
export const collectBlog = data => request.post('/collect/add.do', data)

export const uncollectBlog = data => request.post('/collect/remove.do', data)

export const getCollectStatus = (blogId) => request.get(`/collect/status.do?blogId=${blogId}`)

export const getMyCollections = () => request.get('/collect/my.do')

// 消息通知API
export const getNotifications = () => request.get('/notification/list.do')

export const markNotificationRead = data => request.post('/notification/read.do', data)

export const getUnreadCount = () => request.get('/notification/unread.do')
